﻿using KPIS.GERP.Models;
using KPIS.GERP.Models.Class;
using KPIS.GERP.Models.ICM;
using KPIS.GERP.Models.SYS;
using System;
using System.Data;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.ServiceModel;
using System.Web.Mvc;

namespace KPIS.GERP.WCF.GIMS
{
    [ServiceContract]
    public interface IWarehouseService
    {
        [OperationContract]
        IEnumerable<Warehouse> Select(Warehouse criteriaModel = null, List<string> includeSubObjectString = null);

        [OperationContract]
        IEnumerable<Warehouse> SelectWareHouseOfInternalJobSite(Warehouse criteriaModel = null, List<string> includeSubObjectString = null);

        [OperationContract]
        int Insert(Warehouse m, int createByUserId);

        [OperationContract]
        void Update(Warehouse model, int updateByUserId);

        [OperationContract]
        void Delete(int id, int deleteByUserId);

        [OperationContract]
        IEnumerable<KPIS.GERP.Models.ICM.WarehousePermit> SelectWarehousePermit(WarehousePermit criteriaModel = null,
                                                                                List<string> includeSubObjectString =
                                                                                    null);

        [OperationContract]
        int InsertPermit(WarehousePermit model, int createByUserId);

        [OperationContract]
        void UpdatePermit(WarehousePermit model, int updateByUserId);

        [OperationContract]
        void DeletePermit(int id, int deleteByUserId);

        [OperationContract]
        List<SelectListItem> SelectListWarehouse(int? WhId);

        [OperationContract]
        List<SelectListItem> LoadJobSiteSelectList(int? WareHouseId, bool insertBlankAtFirst = true);

        [OperationContract]
        string SelectNameWareHouse(int? WhId);

    }

    #region Warehouse
    [ServiceErrorBehavior(typeof(ElmahErrorHandler))]
    public class WarehouseService : IWarehouseService
    {
        GERPContext db = new GERPContext();

        public List<Warehouse> SelectMasLookUp()
        {
            using (var context = new GERPContext())
            {
                return (from r in context.Warehouses.Include("MasLookUp")
                        where r.RecordStatus != Models.SYS.RecordStatus.DeletedStatus
                        select r).ToList();
            }

        }


        public List<SelectListItem> SelectListWarehouse(int? WhId)
        {
            var list = new List<SelectListItem>();
            //list.Add(new SelectListItem { Selected = true, Text = "....เลือกคลังพัสดุ....", Value = "" });

            try
            {
                List<Models.ICM.Warehouse> listWarehouse = (from m in db.Warehouses
                                                         where m.RecordStatus != Models.SYS.RecordStatus.DeletedStatus
                                                         select m).ToList();

                foreach (var warehouse in listWarehouse)
                {
                    var item = new SelectListItem { Text = warehouse.Name, Value = warehouse.WhId.ToString() };
                    if (warehouse.WhId == WhId) item.Selected = true;
                    list.Add(item);
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }

            return list;
        }

        public List<SelectListItem> LoadJobSiteSelectList(int? WareHouseId, bool insertBlankAtFirst = true)
        {
            var data = new List<SelectListItem>();

            try
            {
                List<Models.ICM.Warehouse> listWarehouse = (from m in db.Warehouses
                                                            where m.RecordStatus != Models.SYS.RecordStatus.DeletedStatus
                                                            select m).ToList();

                if (insertBlankAtFirst) data.Add(new SelectListItem { Text = string.Empty, Value = string.Empty });
                foreach (var warehouse in listWarehouse)
                {
                    var item = new SelectListItem { Text = warehouse.Name, Value = warehouse.WhId.ToString() };
                    if (warehouse.WhId == WareHouseId) item.Selected = true;
                    data.Add(item);
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }

            return data;
        }

        public IEnumerable<KPIS.GERP.Models.ICM.Warehouse> Select(Warehouse criteriaModel = null, List<string> includeSubObjectString = null)
        {
            try
            {
                using (var context = new GERPContext(false))
                {
                    IQueryable<Warehouse> query = context.Warehouses;

                    if (includeSubObjectString != null)
                    {
                        query = includeSubObjectString.Aggregate(query, (current, includePath) => current.Include(includePath));
                    }

                    if (criteriaModel != null)
                    {
                        object[] param;
                        query = query.Where(KPIS.GERP.Models.Class.Utility.GenerateWhereString(criteriaModel, out param), param);
                    }

                    return query.ToList();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public IEnumerable<Warehouse> SelectWareHouseOfInternalJobSite(Warehouse criteriaModel = null, List<string> includeSubObjectString = null)
        {
            try
            {
                using (var context = new GERPContext(false))
                {
                    IQueryable<Warehouse> query = context.Warehouses;

                    if (includeSubObjectString != null)
                    {
                        query = includeSubObjectString.Aggregate(query, (current, includePath) => current.Include(includePath));
                    }

                    if (criteriaModel != null)
                    {
                        object[] param;
                        query = query.Where(KPIS.GERP.Models.Class.Utility.GenerateWhereString(criteriaModel, out param), param);
                    }

                    query = query.Where(o => o.JobSite.JobSiteTypeId == 2);

                    return query.ToList();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public int Insert(Warehouse m, int createByUserId)
        {
            try
            {
                using (var context = new GERPContext())
                {
                    m.RecordStatus = RecordStatus.UsedStatus;
                    m.CreatedBy = createByUserId;
                    m.UpdatedWhen = DateTime.Now;
                    context.Warehouses.Add(m);
                    context.SaveChanges();

                    return m.WhId;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Update(Warehouse model, int updateByUserId)
        {
            try
            {
                using (var context = new GERPContext())
                {
                    context.Entry(model).State = EntityState.Modified;
                    model.UpdatedBy = updateByUserId;
                    model.UpdatedWhen = DateTime.Now;
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Delete(int id, int deleteByUserId)
        {
            try
            {
                using (var context = new GERPContext())
                {
                    var modelToDelete = context.Warehouses.Find(id);
                    if (modelToDelete == null) return;

                    context.Entry(modelToDelete).State = EntityState.Modified;
                    modelToDelete.RecordStatus = RecordStatus.DeletedStatus;
                    modelToDelete.UpdatedBy = deleteByUserId;
                    modelToDelete.UpdatedWhen = DateTime.Now;
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string SelectNameWareHouse(int? WhId)
        {
            using (GERPContext db = new GERPContext(false))
                try
                {
                    string Tmp = null;
                    if (WhId != 0)
                    {
                        string WareHouseName = (from m in db.Warehouses
                                                where m.WhId == WhId
                                                select m.Name).First().ToString();
                        Tmp = WareHouseName;
                    }
                    else
                    {
                        Tmp = "";
                    }
                    return Tmp;

                }
                catch (Exception ex)
                {
                    throw ex;
                }
        }
    #endregion


        #region WarehousePermit

        public IEnumerable<KPIS.GERP.Models.ICM.WarehousePermit> SelectWarehousePermit(WarehousePermit criteriaModel = null, List<string> includeSubObjectString = null)
        {
            try
            {
                using (var context = new GERPContext(false))
                {
                    IQueryable<WarehousePermit> query = context.WarehousePermits;

                    if (includeSubObjectString != null)
                    {
                        query = includeSubObjectString.Aggregate(query, (current, includePath) => current.Include(includePath));
                    }

                    if (criteriaModel != null)
                    {
                        object[] param;
                        query = query.Where(KPIS.GERP.Models.Class.Utility.GenerateWhereString(criteriaModel, out param), param);
                    }

                    return query.ToList();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public int InsertPermit(WarehousePermit model, int createByUserId)
        {
            try
            {
                using (var context = new GERPContext())
                {
                    model.RecordStatus = RecordStatus.UsedStatus;
                    model.CreatedBy = createByUserId;
                    model.CreatedWhen = DateTime.Now;
                    context.WarehousePermits.Add(model);
                    context.SaveChanges();
                    return model.WarehousePermitId;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void UpdatePermit(WarehousePermit model, int updateByUserId)
        {
            try
            {
                using (var context = new GERPContext())
                {
                    var existData = context.WarehousePermits
                        .Where(m => m.JobSiteId == model.JobSiteId
                            && m.WhId == model.WhId
                            && m.RecordStatus != RecordStatus.DeletedStatus
                            && m.WarehousePermitId != model.WarehousePermitId).ToList();

                    if (existData.Count == 0)
                    {
                        context.Entry(model).State = EntityState.Modified;
                        model.UpdatedBy = updateByUserId;
                        model.UpdatedWhen = DateTime.Now;
                        context.SaveChanges();
                    }
                    else
                    {
                        throw new Exception("เกิดข้อผิดพลาด!! ข้อมูลนี้มีบันทึกอยู่แล้ว");
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void DeletePermit(int id, int deleteByUserId)
        {
            try
            {
                using (var context = new GERPContext())
                {
                    var modelToDelete = context.WarehousePermits.Find(id);
                    if (modelToDelete == null) return;

                    context.Entry(modelToDelete).State = EntityState.Modified;
                    modelToDelete.RecordStatus = RecordStatus.DeletedStatus;
                    modelToDelete.UpdatedBy = deleteByUserId;
                    modelToDelete.UpdatedWhen = DateTime.Now;
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion
    }
}
